import { Component, toNative } from 'vue-facing-decorator'
import TableRender, { type TableRenderColumnTypes } from '@/render/TableRender'
import type { FilterDto } from '@/render/FilterRender'
import type { VxeColumnSlotTypes, VxeGridPropTypes, VxeTableDataRow } from 'vxe-table'
import type { AnyObject } from '@/types'
import {
    getKeyToEnum,
    InvoiceCheckStatusCnEnum,
    InvoiceTypeCnEnum,
    InvoiceUploadStatusCnEnum
} from '@/const/enum'
import DialogUpload from './components/DialogUpload'
import { cancelInvoiceUplaod, exportInvoice, getInvoiceList, uploadInvoice, uploadInvoiceZip, uploadOpenCompany } from '@/api/invoice'
import type { InvoiceDto, InvoiceReqDto } from '@/api/invoice/types'
import { confirm, downloadFile, getCompanyListByName } from '@/utils/util'
import PreviewImageOrPdf from '@/components/preview-media/PreviewImageOrPdf'
import { Button, DatePicker, message, Tooltip, type UploadFile } from 'ant-design-vue'
import { DownloadOutlined, FileExclamationOutlined, UploadOutlined } from '@ant-design/icons-vue'
import { h } from 'vue'
import { getSaleList } from '@/api/sale'
import { getSystemUserList } from '@/api/system'
import dayjs,  {type Dayjs } from 'dayjs'
import DialogExportApplyCompany from './components/DialogExportApplyCompany'
@Component
export class Uploaded extends TableRender {
    showUploadZip = false
    showUpload = false
    showUploadTicketCompany = false
    showExportApplyCompany = false
    params = {} as InvoiceReqDto

    uploadFile = null as File | null

    curItem = {} as InvoiceDto

    uploadMonth = dayjs().format('YYYY-MM') // 导入开票公司的月份

    filterConfig() {
        return {
            companyName: {
                name: '客户名称',
                element: 'autoComplete',
                class: 'w-full',
                placeholder: '请输入后选择',
                optionsType: 'company'
            },
            deptId: {
                name: '所属分组',
                element: 'select',
                optionsType: 'saleDept',
                callback: {
                    change: async (ev: number) => {
                        this.filters.salesId.value = ''
                        if (ev) {
                            this.filters.salesId.options = (await getSystemUserList({
                                deptId: ev,
                                pageNum: 1,
                                pageSize: 999
                            })).rows?.map(i => {
                                return {
                                    label: i.nickName,
                                    value: i.userId
                                }
                            })
                        } else {
                            this.filters.salesId.options = (await getSaleList()).map(i => {
                                return {
                                    label: i.saleName,
                                    value: i.saleId
                                }
                            })
                        }
                    }
                }
            },
            salesId: {
                name: '所属商务',
                element: 'select',
                optionsType: 'saleList'
            },
            applicationMonth: {
                name: '申请月份',
                element: 'datetime',
                params: {
                    type: 'month',
                    valueFormat: 'YYYY-MM'
                }
            },
            month: {
                name: '发票月份',
                element: 'datetime',
                params: {
                    type: 'month',
                    valueFormat: 'YYYY-MM'
                }
            },
            receiptIds: {
                name: '收款账户',
                element: 'select',
                multiple: true,
                params: {
                    maxTagCount: 1
                },
                optionsType: 'receipt',
                placeholder: '请选择（可多选）'
            }
        } as FilterDto
    }

    tableColumnConfigOld = () =>
        [
            {
                type: 'checkbox',
                fixed: 'left',
                width: 50
            },
            {
                field: 'operate',
                title: '操作',
                width: 50,
                fixed: 'left', 
                params: {
                    buttons: [
                        {
                            text: '预览',
                            type: 'preview',
                            previewProp: 'invoiceUrl'
                        },
                        {
                            text: '上传发票',
                            icon: UploadOutlined,
                            event: (row: InvoiceDto) => {
                                this.onUpload(row)
                            }
                        },
                        {
                            text: '消除异常状态',
                            icon: UploadOutlined,
                            event: (row: InvoiceDto) => {
                                this.handleCancelAbnormal([row.id])
                            }
                        },
                    ]
                },
                slots: {
                    default: 'tooltipButtons'
                }
            },
            {
                field: 'companyName',
                title: '客户名称',
                width: 200
            },
            {
                field: 'type',
                title: '发票类型',
                formatter: ({ row }) => {
                    return InvoiceTypeCnEnum[row.type]
                }
            },
            {
                field: 'checkStatus',
                title: '核对状态',
                slots: {
                    default: ({
                        row,
                        column
                    }: VxeColumnSlotTypes.ContentSlotParams<InvoiceDto>) => {
                        const map = {
                            0: 'green',
                            1: 'red',
                            2: 'blue-200'
                        }
                        return (
                            <div class="flex items-center">
                                <div
                                    class={`w-6px h-6px rounded-full mr-4px bg-${map[row.checkStatus as keyof typeof map]}`}
                                ></div>
                                {row.checkStatus === InvoiceCheckStatusCnEnum.异常 ? (
                                    <Tooltip title="异常原因：发票金额不符">
                                        <div class="cursor-pointer">异常</div>
                                    </Tooltip>
                                ) : (
                                    <div>{InvoiceCheckStatusCnEnum[row.checkStatus]}</div>
                                )}
                            </div>
                        )
                    }
                }
            },
            {
                field: 'month',
                title: '发票月份'
            },
            {
                field: 'applyTime',
                title: '申请时间',
                width: 150
            },
            {
                field: 'amount',
                title: '发票金额',
                slots: {
                    default: 'price' 
                }
            },
            {
                field: 'rechargeAmount',
                title: '充值金额',
                slots: {
                    default: 'price'
                }
            },
            {
                field: 'uploadTime',
                title: '上传日期',
                width: 150
            },
            {
                field: 'updateTime',
                title: '开票日期',
                width: 150
            },
            {
                field: 'salesName',
                title: '归属业务'
            },
            {
                field: 'bankName',
                title: '收款账户',
                width: 200
            }
        ] as TableRenderColumnTypes<InvoiceDto>

    onUploadZip() {
        this.showUploadZip = true
    }

    onUpload(row: InvoiceDto) {
        this.showUpload = true
        this.curItem = row
    }

    async onExport() {
        this.params = this.getFilters() as InvoiceReqDto
        this.showExportApplyCompany = true
        // params.status = InvoiceUploadStatusCnEnum.已上传
        // const res = await exportInvoice(params)
        // downloadFile(res)
    }

    async onConfirm(data: { file: UploadFile[]; close: () => void }, type: string) {
        if (!data.file?.length) {
            message.warning('请先上传文件')
            return
        }
        const fileData = new FormData()
        fileData.append('file', data.file[0].originFileObj as File)
        if (type === 'zip') {
            await uploadInvoiceZip(fileData)
        } else {
            await uploadInvoice(fileData, this.curItem.id)
        }
        message.success('上传成功')
        this.reloadPage()
        data.close()
    }

    async onUplaodOpenCompany(data: { file: UploadFile[]; close: () => void },) {
        if (!data.file?.length) {
            message.warning('请先上传文件')
            return
        }
        const formData = new FormData()
        formData.append('month', this.uploadMonth)
        formData.append('file', data.file[0].originFileObj as File)
        await uploadOpenCompany(formData)
        message.success('上传成功')
        this.showUploadTicketCompany = false
        this.reloadPage()
    }

    // 处理撤销异常发票
    async handleCancelAbnormal(ids: number[]) {
        await confirm('确定撤销吗？', '提示')
        await cancelInvoiceUplaod({
            ids
        })
        message.success('处理成功')
        this.reloadPage()
    }
    // 批量撤销
    onCancelAbnormal() {
        const ids = this.ref.getCheckboxRecords()?.map(i => i.id)
        if (!ids.length) {
            message.warn('请选择要撤销的发票')
            return
        }
        this.handleCancelAbnormal(ids)
    }

    // 下载开票公司模板
    onDownloadTemplate(ev: Event) {
        ev.stopPropagation()
        console.log('下载模板')
        downloadFile('https://bullet001.oss-cn-shanghai.aliyuncs.com/template/excel/pay/open_invoice_template.xlsx')
    }

    onUploadTicketCompany() {
        this.showUploadTicketCompany = true
    }

    onLoadData(page: number, size: number, filters: AnyObject) {
        filters.receiptIds = filters.receiptIds?.join(',') ?? ''
        return getInvoiceList({
            pageNum: page,
            pageSize: size,
            status: InvoiceUploadStatusCnEnum.已上传,
            ...filters
        })
    }

    renderRightBtns() {
        return (
            <div class="flex">
                <Button type="text" icon={h(FileExclamationOutlined)} onClick={this.onCancelAbnormal}>
                    批量消除异常
                </Button>
                <Button type="text" icon={h(UploadOutlined)} onClick={this.onUploadTicketCompany}>
                    导入开票公司
                </Button>
                <Button type="text" icon={h(DownloadOutlined)} onClick={this.onExport}>
                    导出企业信息
                </Button>
                <Button type="text" icon={h(UploadOutlined)} onClick={this.onUploadZip}>
                    上传发票
                </Button>
            </div>
        )
    }

    render() {
        return (
            <>
                {super.render()}
                <DialogUpload
                    v-model:show={this.showUploadZip}
                    onConfirm={(event) => this.onConfirm(event, 'zip')}
                    accept=".zip"
                    v-slots={{
                        default: () => {
                            return (
                                <div class="text-sm text-black-200">
                                    {/* <div>
                                        上传文件名称格式：电子签__年-月.zip；如：电子签__2022-01.zip
                                    </div> */}
                                    <div>
                                        上传文件名称格式：日日保__年-月.zip；如：日日保__2022-01.zip
                                    </div>
                                </div>
                            )
                        }
                    }}
                />

                <DialogUpload
                    v-model:show={this.showUpload}
                    onConfirm={(event) => this.onConfirm(event, 'single')}
                />

                {/* 导入开票公司 */}
                <DialogUpload
                    v-model:show={this.showUploadTicketCompany}
                    onConfirm={(event) => this.onUplaodOpenCompany(event)}
                    accept=".xlsx,.xls"
                    v-slots={{
                        filter: () => {
                            return <div class="mb-12px flex items-center">
                                <div><span class="text-error mr-4px">*</span>开票月份：</div>
                                <DatePicker v-model:value={this.uploadMonth} picker="month" format="YYYY-MM" valueFormat="YYYY-MM" />
                            </div>
                        },
                        default: () => {
                            return (
                                <div class="text-sm text-black-200">
                                    <div>
                                        下载导入模板，根据模板提示完善内容：<span class="text-blue-100" onClick={this.onDownloadTemplate}>下载模板</span>
                                    </div>
                                </div>
                            )
                        }
                    }}
                />

                <DialogExportApplyCompany v-model:show={this.showExportApplyCompany} params={this.params}/>
            </>
        )
    }
}

export default toNative(Uploaded)
